import { ref } from 'vue'
import Cookies from 'js-cookie'
import { defineStore } from 'pinia'
import {fetchRemoveAddress, fetchAddressList, fetchChangeAddress} from "@/service/address";
interface AddressParam {
  id?: number
  cityName: string
  area: string
  addr: string
  lat: number
  lng: number
  name: string
  phone: string
  isDefault: boolean
}
export type Address = {
  id?: string
  name: string
  phone: string
  province: string
  cityId: string
  city: string
  area: string
  addr: string
}
export const useAddress = defineStore('address', () => {
  const setDefaultId = (id: string) => {
    try {
      localStorage.setItem('defaultAddressId', id)
      Cookies.set('defaultAddressId', id, { expires: 365 })
    } catch(e: any) {
      console.log(e)
    }
    address.value.defaultId = id
  }

  const getDefaultId = () => {
    return localStorage.getItem('defaultAddressId') || Cookies.get('defaultAddressId') || ''
  }
  const address = ref({
    addressList: <Address[]>[],
    defaultId: getDefaultId(),
    selectedId: '',
  })

  const getAddressList = async () => {
    const res = await fetchAddressList()
    address.value.addressList = res.data || []
    return address.value.addressList
  }

  const selectAddress = async (id: string) => {
    address.value.selectedId = id
    setDefaultId(id)
  }

  const getSelectedAddress = () => {
    return getAddress(address.value.selectedId || getDefaultId())
  }

  const getAddress = (id: string) => {
    const target = address.value.addressList.find((address) => address.id === id)
    return target
  }

  const addOrUpdateAddress = async (params: AddressParam) => {
    const res = await fetchChangeAddress(params)
    if(params.isDefault) {
      setDefaultId(res.data?.id||'')
    }
    getAddressList()
  }

  const deleteAddress = async (id: string) => {
    await fetchRemoveAddress(id)
    if(id === address.value.defaultId) setDefaultId('')
    if(id === address.value.selectedId) address.value.selectedId = ''
    address.value.addressList = address.value.addressList.filter(item => item.id !== id)
  }

  return { address, getAddressList, selectAddress, getSelectedAddress, getAddress, addOrUpdateAddress, deleteAddress, setDefaultId }
})
